<template>
    <div>
        <div style="background-color: #f1f8e9; padding: 15px; margin-bottom: 20px; border-radius: 8px; border-left: 4px solid #8BC34A;">
            <h3 style="color: #558B2F; margin-top: 0;">🔄 技术解释：异步操作状态侦听</h3>
            <p><strong>状态管理：</strong>通过status数据追踪异步操作的不同阶段（Idle、Running、Success、Error）。</p>
            <p><strong>异步操作监听：</strong>使用侦听器监听status变化，可以在状态改变时执行相应的副作用操作。</p>
            <p><strong>Promise处理：</strong>结合async/await和try-catch处理异步操作，确保错误状态也能被正确捕获和处理。</p>
            <p><strong>用户反馈：</strong>通过状态变化为用户提供实时的操作反馈，提升用户体验。</p>
        </div>
        <p>Status: {{ status }}</p>
        <button @click="startAsyncOperation">Start Async Operation</button>
    </div>
</template>
<script>
export default{
    data() {
        return {
            status: 'Idle',
        };
    },
    methods:{
        async startAsyncOperation() {
            this.status = 'Runing';
            try{
                await this.doAsyncOperation();
                this.status = 'Success';
            }catch(error){
                this.status = 'Error';
                console.error(error);
            }
        },
        async doAsyncOperation(){
            return new Promise((resolve,reject) => {
                setTimeout(() => {
                    const random = Math.random();
                    if(random < 0.8){
                        resolve('Async operation completed');
                    }else{
                        reject(new Error('Async operation failed'));
                    }
                },2000);
            });
        },
    },
    watch:{
        status(newValue){
            console.log('Status changed:',newValue);
        },       
    },
};
</script>